var layerLoad;

/**
 * 页面初始化加载
 */
(function(){
	initBannerList(1);
    initBannerUrl(1);
})();

var layerNumber = null;
/*初始化select框*/
var goodsSlectTxt="";
var classSlectTxt="";
function initBannerUrl(currentPage){
    $.ajax({
        url : $api.banner.selectProductBasicInfoForBanner,
        type : "GET",
        dataType : "JSON",
        contentType : 'application/json',
        beforeSend : function () {
        },
        success : function(data) {
            goodsSlectTxt="";
            $.each(data.msg,function(index,data){
                var urlTxt=data.linkUrlPostfix+data.id;
                goodsSlectTxt+="<option value="+urlTxt+">"+data.name+"</option>";
            });
            $(".goodsSlect").html(goodsSlectTxt);
        },
        error : function() {
            layer.msg('网络异常，请稍后再试', {icon: 2});
        }
    });
    /*商品分类*/
    $.ajax({
        url : $api.banner.selectProductCategoryBasicInfoForBanner,
        type : "GET",
        dataType : "JSON",
        contentType : 'application/json',
        beforeSend : function () {
        },
        success : function(data) {
            classSlectTxt="";
            $.each(data.msg,function(index,data){
            	var urlTxt=data.linkUrlPostfix+data.id;
                classSlectTxt+="<option value="+urlTxt+">"+data.name+"</option>";
            })
            $(".classSlect").html(classSlectTxt);
        },
        error : function() {
            layer.msg('网络异常，请稍后再试', {icon: 2});
        }
    });
};
/*初始化list*/
var linkUrl="";
function initBannerList(currentPage){
	$.ajax({
		url : $api.banner.selectBanners,
		type : "GET",
		dataType : "JSON",
		contentType : 'application/json',
		beforeSend : function () {
			layerLoad = layer.load();
		},
		success : function(data) {
			if(!$checkRemouteStatus(data)){
				layer.close(layerLoad);
				return;
			}
			layui.use('laytpl', function() {
				var laytpl = layui.laytpl;
				laytpl(sysBannerListTpl.innerHTML).render(data, function(html) {
					$('#sys-banner-list').html(html)
				});
			});
			layui.use('laypage', function() {
				layui.laypage({
					cont: $('#sys-product-list-body-page'),
					pages: data.totalPage,
					groups: 2,
					curr: data.currentPage,
					skip: true,
					jump: function (obj,first) {
						if(!first){
							initBannerList(obj.curr);
						}
					}
				});
			});
			layer.close(layerLoad);
		},
		error : function() {
			layer.close(layerLoad);
			layer.msg('网络异常，请稍后再试', {icon: 2});
		}
	});
};

/**
 * 详情查询
 */
var bannerImgFlag='';
$('#sys-banner-list').on('click','.btn-system-banner-update',function(){
	$.ajax({
		url : $api.banner.selectBannerById+"?bannerId="+$(this).attr("id"),
		type : "GET",
		dataType : "JSON",
		contentType : 'application/json',
		beforeSend : function () {
			layerLoad = layer.load();
		},
		success : function(data,e) {
			if(!$checkRemouteStatus(data)){
				layer.close(layerLoad);
				return;
			}
			var dataObj=data.msg;
            //linkUrl=dataObj.linkUrlPre;
			bannerImgFlag=dataObj.orders;
			$('#desctription').val(dataObj.desctription);
			$('#categoryName').val(dataObj.categoryName);
			$("#save").attr("bannerId",dataObj.id);
			if(dataObj.categoryName==="上"){
				$("#imgPrompt").text("可上传多张图片,图片尺寸:728px*691px");
			}else{
				$("#imgPrompt").text("仅上传1张图片,图片尺寸为361px*285px");
			}
			var productImgTxt="";
         	$.each(dataObj.bannerImages,function(index,data){
                productImgTxt+="<div class='am-g am-padding-vertical am-margin-bottom' style='border:1px solid #cccccc;'>";
                productImgTxt+="<div class='am-u-sm-6 am-margin-bottom-xs'><img class='am-thumbnail' flagImg="+data.isNew+" src="+data.thumbnail+"  alt='展示图片' />";
                productImgTxt+="<a href='javascript:void(0)' onclick='delImg(this)' class='am-close am-close-alt am-icon-times'></a></div><div class='am-u-sm-6'>";
                productImgTxt+="<label>链接类型</label><select class='linkType'>";
                if(data.orders==1){
                    productImgTxt+="<option value='1' selected = 'selected'>外部链接</option><option value='2'>商品详情</option><option value='3'>商品分类</option></select></div >";
				}
                if(data.orders==2){
                    productImgTxt+="<option value='1'>外部链接</option><option value='2' selected = 'selected'>商品详情</option><option value='3'>商品分类</option></select></div >";
                }
                if(data.orders==3){
                    productImgTxt+="<option value='1'>外部链接</option><option value='2'>商品详情</option><option value='3' selected = 'selected'>商品分类</option></select></div >";
                }
                productImgTxt+="<div  class='am-u-sm-6 classSlectBox'><label>商品分类</label><select class='classSlect'>"+classSlectTxt+"</select></div><div  class='am-u-sm-6 goodsSlectBox'><label>商品详情</label>";
                productImgTxt+="<select class='goodsSlect'>"+goodsSlectTxt+"</select></div><div class='am-u-sm-6'><label>链接路径</label><input class='linkUrl' placeholder='请输入链接路径...' required='required' disabled='disabled' type='text' class='linkUrl' value="+data.linkurl+">";
                productImgTxt+="</div></div></div>";
         	});
			$("#bannerImgBox").html(productImgTxt);
			layer.close(layerLoad);
		},
		error : function() {
			layer.close(layerLoad);
			layer.msg('网络异常，请稍后再试', {icon: 2});
		}
	});
	layerNumber = layer.open({
		type : 1,
		title : 'banner',
		area : 'auto',
		maxWidth : '1000px',
		content : $('#sys-product-update-model'),
		cancel : function(){
			$('#sys-product-form-update')[0].reset();
			$('#sysProductImgUrlUpdate').attr('src',$assets.headChooseIcon);
		}
	});
});
/*ImgUrl,设置*/
$("#bannerImgBox").on("change",".linkType",function(){
	var classSlectBox=$(this).parent().parent().find(".classSlectBox");
	var goodsSlectBox=$(this).parent().parent().find(".goodsSlectBox");
	var linkUrl=$(this).parent().parent().find(".linkUrl");
    classSlectBox.css("display","none");
    goodsSlectBox.css("display","none");
    linkUrl.attr("disabled","disabled");
    linkUrl.val("链接自动生成");
	if($(this).val() === "2"){
        goodsSlectBox.css("display","block");
	}
    if($(this).val() === "3"){
        classSlectBox.css("display","block");
    }
    if($(this).val() === "1"){
        linkUrl.val("");
        linkUrl.removeAttr("disabled");
    }
});
/*select数据回显*/
$("#bannerImgBox").on("change",".goodsSlect",function(){
    var linkUrlTxt=linkUrl+$(this).parent().parent().find(".goodsSlect").val();
    console.log(linkUrlTxt);
	$(this).parent().parent().find(".linkUrl").val(linkUrlTxt);
});
$("#bannerImgBox").on("change",".classSlect",function(){
    var linkUrlTxt=linkUrl+$(this).parent().parent().find(".classSlect").val();
    console.log(linkUrlTxt);
    $(this).parent().parent().find(".linkUrl").val(linkUrlTxt);
});

$("#save").click(function(){
	var productData={};
    var linkUrlEr="";
	$("#sys-product-form-update  .am-form-group > input").each(function(index,dom){
		if($(dom).attr("id")!==undefined){
			productData[$(dom).attr("id")]=$(dom).val();
		}
	});
	productData["desctription"]=$('#desctription').val();
	productData["categoryName"]=$('#categoryName').val();
	productData["id"] = $("#save").attr("bannerId");
	if($("#bannerImgBox .am-g").length==0){
        layer.msg('至少要有一张展示图片', {icon: 2});
        return;
	}
	if(bannerImgFlag !== 1  && $("#bannerImgBox .am-g").length>1){
		layer.msg('只能有一张展示图片', {icon: 2});
		return;
	}
	var productImgArr=[];
	$("#bannerImgBox .am-g").each(function(index,damo){
		var productImgObj={};
		productImgObj["isNew"]=$(damo).find("img").attr("flagImg");
		productImgObj["bannerImageStr"]=$(damo).find("img").attr("src");
		var isLinkType=$(damo).find(".linkType").val();
        var goodsSlect=$(damo).find(".goodsSlect");
        var classSlect=$(damo).find(".classSlect");
        var linkUrl2=$(damo).find(".linkUrl").val();
        productImgObj["orders"]=isLinkType;
        if(isLinkType === "2"){
            linkUrlEr="/"+goodsSlect.val();
        }
        if(isLinkType === "3"){
            linkUrlEr="/product/remote/"+classSlect.val();
        }
        if(isLinkType === "1"){
            productImgObj["linkurl"]=linkUrl2;
        }else{
            productImgObj["linkurl"]=linkUrlEr;
        }
		productImgArr.push(productImgObj);
	});
	productData["bannerImages"]=productImgArr;
	delete productData.productFileImg;/*多余数据*/
	$.ajax({
        url: $api.banner.updateBanner,
        type: "POST",
        dataType: "JSON",
        contentType : 'application/json',
        data :  JSON.stringify(productData) ,
        beforeSend: function () {
            layerLoad = layer.load();
        },
        success: function (data) {
        	layer.close(layerLoad);
        	var dataObj=data.msg;
            if(data.code == '111111'){
                layer.msg(data.msg, {icon: 2});
            }else{
            	layer.msg(data.msg, {icon: 1});
            	initBannerList(1);
            	layer.close(layerNumber);
            	 $("#sys-product-update-model").css("display","none");
            }
        },
        error: function () {
        	layer.msg("网络开小差啦", {icon: 2});
        }
    });
});

//64
window.onload = function(){
    var input = document.getElementById("productFileImg");
    if ( typeof(FileReader) === 'undefined' ){
    	layer.msg("抱歉，你的浏览器不支持 FileReader，请使用现代浏览器操作！", {icon: 2});
        input.setAttribute( 'disabled','disabled' );
    } else {
        input.addEventListener( 'change',readFile,false );
    }
}
function readFile(){
    var file = this.files[0];
    console.log(this.files);
    var productImg=$("#bannerImgBox");
    //这里我们判断下类型如果不是图片就返回 去掉就可以上传任意文件
    if(!/image\/\w+/.test(file.type)){
    	layer.msg("请确保文件为图像类型", {icon: 2});
        return false;
    }
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function(e){
		//验证
		if(file.size/1024>200){	//图片大小限制
			layer.msg("图片不得大于200K.....", {icon: 2});
			return
			}
		imgTxt="<div class='am-g am-padding-vertical am-margin-bottom' style='border:1px solid #cccccc;'>";
		imgTxt+="<div class='am-u-sm-6 am-margin-bottom-xs'><img class='am-thumbnail' flagImg='-1' src="+this.result+"  alt='展示图片' />";
		imgTxt+="<a href='javascript:void(0)' onclick='delImg(this)' class='am-close am-close-alt am-icon-times'></a></div><div class='am-u-sm-6'>";
		imgTxt+="<label>链接类型</label><select class='linkType'><option value='1'>外部链接</option><option value='2'>商品详情</option><option value='3'>商品分类</option></select></div >";
		imgTxt+="<div  class='am-u-sm-6 classSlectBox'><label>商品分类</label><select class='classSlect'>"+classSlectTxt+"</select></div><div  class='am-u-sm-6 goodsSlectBox'><label>商品详情</label>";
		imgTxt+="<select class='goodsSlect'>"+goodsSlectTxt+"</select></div><div class='am-u-sm-6'><label>链接路径</label><input class='linkUrl' type='text' class='linkUrl'  placeholder='请输入链接路径...' required='required'>";
        imgTxt+="</div></div></div>";
		productImg.append(imgTxt);//输出
		$("#productFileImg").val("");
    }
}
/*删除图片*/
function delImg (othis){
	$(othis).parent().parent().remove();
};